<template>
  <div>
    <!-- 1 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 2 卡片区域 -->
    <el-card>
      <!-- 2.1 alert警告 -->
      <el-alert title="注意:只允许为第三级分类设置相关参数" type="warning" show-icon :closable="false"> </el-alert>
      <!-- 2.2 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>

          <!-- 2.2.1 选择商品分类的级联选择框 -->
          <!-- :options用来指定数据源 -->
          <!-- :props用来指定配置对象,在data里自己定义 -->
          <!-- v-model 用来保存选中的id值,是个数组,因为可能选中2级 -->
          <!-- @change 当级联选择项改变 -->
          <el-cascader v-model="selectedParamsKeys" :options="cateList" :props="cateProps" @change="handleChange"></el-cascader>
        </el-col>
      </el-row>

      <!-- 2.3 tab页签区域 -->
      <!-- v-model表示被激活的页签的name名称动态绑定到activeName上 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 2.3.1添加动态参数的面板 将标签页改为many -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数按钮,:disabled禁用属性 -->
          <el-button size="mini" type="primary" :disabled="isButtonDisabled" @click="addDialogVisible = true">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <!-- 1 作用域插槽接收已经被变为数组的itiem.attr_vals  -->
              <template slot-scope="scope">
                <!-- 1.1 循环渲染tag标签,item就是每一行的每个蓝色小标签 -->
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i, scope.row)">{{ item }}</el-tag>
                <!-- 1.2 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 1.3 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">修改</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 2.3.2 添加静态属性的面板 将标签页改为only -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性按钮 -->
          <el-button size="mini" type="primary" :disabled="isButtonDisabled" @click="addDialogVisible = true">添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <!-- 作用域插槽接收已经被变为数组的itiem.attr_vals  -->
              <template slot-scope="scope">
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i, scope.row)">{{ item }}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 1.3 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">修改</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 1! 添加参数或属性对话框 -->
    <el-dialog :title="'添加' + titleText" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <!-- 添加表单 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 2! 修改按钮对话框 -->
    <el-dialog :title="'修改' + titleText" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <!-- 添加表单 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //商品分类列表
      cateList: [],
      //配置级联菜单中数据如何展示
      cateProps: {
        //值都是根据请求返回的数据定义的
        //value是选中的值
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      //级联选择框双向绑定到的id数组
      selectedParamsKeys: [],
      //被激活的页签的名称,默认为用户管理
      activeName: 'many',
      //用来保存动态参数数据
      manyTableData: [],
      //用来保存静态属性数据
      onlyTableData: [],
      //添加参数或属性对话框隐藏与显示
      addDialogVisible: false,
      //添加参数的表单数据对象
      addForm: {
        attr_name: ''
      },
      //添加表单的验证规则对象
      addFormRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      },
      //修改按钮对话框隐藏与显示
      editDialogVisible: false,
      //修改参数.属性对话框中的表单
      editForm: {
        attr_name: '',
        attr_id: ''
      },
      //修改表单的验证规则
      editFormRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      }
      //控制按钮与文本框的切换显示.默认不显示
      //inputVisible: false,
      //文本框中输入的内容
      //inputValue: ''
    }
  },
  created() {
    // 页面一加载,就获取所有商品分类1.6.1
    this.getCateList()
  },
  methods: {
    //获取所有的商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')

      if (res.meta.status !== 200) {
        return this.$message.error('获取分类数据失败')
      }
      //将数据列表赋值给cateList
      this.cateList = res.data
      //console.log(this.cateList)
    },
    //级联选择框选择项变化时,会触发该函数
    handleChange() {
      this.getParamsData()
    },
    //tab页签点击事件的处理函数
    handleTabClick() {
      console.log('动态/静态' + this.activeName)
      this.getParamsData()
    },
    // 获取三级属性的列表数据
    async getParamsData() {
      // 证明选中的不是三级分类
      if (this.selectedParamsKeys.length !== 3) {
        this.selectedParamsKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return false
      }
      console.log(this.cateId)
      //是三级分类,获取动态参数和静态属性1.7.1
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName }
      })

      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败！')
      }
      //console.log(res.data)

      //把res.data的attr_vals变成数组形式
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        //添加一个bool值控制文本框的显示或者隐藏
        item.inputVisible = false
        //添加一个inputValue保存文本框值
        item.inputValue = ''
      })
      console.log(res.data)

      if (this.activeName === 'many') {
        //获取的是动态参数
        this.manyTableData = res.data
      } else if (this.activeName === 'only') {
        //获取的是静态属性
        this.onlyTableData = res.data
      }
    },
    // 监听添加参数或属性对话框是否关闭
    addDialogClosed() {
      //重置
      this.$refs.addFormRef.resetFields()
    },
    //表单点击 "确定"按钮
    addParams() {
      //1 当用户点击对话框中的确定时，校验表单
      this.$refs.addFormRef.validate(async valid => {
        //校验不通过
        if (!valid) {
          return this.$message.error('校验不通过')
        }
        //校验通过,发送请求完成添加参数或者属性1.7.2
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.$message.error('添加' + this.titleText + '数据失败')
        }
        this.$message.success('添加' + this.titleText + '数据成功')
        this.addDialogVisible = false
        this.getParamsData()
      })
    },
    //点击动态参数或者静态属性表格的"修改"按钮
    async showEditDialog(attrId) {
      //1 发起请求获取需要修改的那个参数数据1.7.4
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}`, { params: { attr_sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数数据失败')
      }
      //2 将获取到的数据保存起来,再熏染到对话框
      this.editForm = res.data
      //3 显示修改参数.属性对话框
      this.editDialogVisible = true
    },
    //动态参数或者静态属性对话框的"确定"按钮
    async editParams() {
      //表单验证
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('数据验证失败')
        }
        //发送请求完成修改1.7.5
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, { attr_name: this.editForm.attr_name, attr_sel: this.activeName })
        // 获取失败
        if (res.meta.status !== 200) {
          return this.$message.error('数据获取失败')
        }
        //获取成功
        this.$message.success('修改' + this.titleText + '数据成功')
        //关闭对话框
        this.editDialogVisible = false
        //刷新页面
        this.getParamsData()
      })
    },
    // 重置修改表单
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    //删除按钮
    async removeParams(attrId) {
      //弹窗提示用户是否要删除
      const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      //用户取消删除
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      //用户确认删除,发送请求1.7.3
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attrId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数数据失败')
      }
      this.$message.success('删除' + this.titleText + '数据成功')
      this.getParamsData()
    },
    //文本框失去焦点,或摁下Enter都会触发
    async handleInputConfirm(row) {
      //如果输入空字符串或者没输入
      if (row.inputValue.trim().length === 0) {
        //清空数据
        row.inputValue = ''
        //隐藏输入框
        row.inputVisible = false
        return false
      }
      //如果输入的是合法的,就保存在循环的数组里,去空格
      row.attr_vals.push(row.inputValue.trim())
      //然后清空
      row.inputValue = ''
      //恢复成按钮
      row.inputVisible = false
      this.saveAttrVals(row)
    },
    //点击按钮,显示输入文本框
    showInput(row) {
      row.inputVisible = true
      //   让文本框自动获得焦点
      // this.$nextTick
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除蓝色tag标签
    handleClose(i, row) {
      // role.attr_vals 是数组 ,splice切割完会保存
      row.attr_vals.splice(i, 1)
      //删除完保存数据库
      this.saveAttrVals(row)
    },
    //对蓝色tag的改变,保存数据库
    async saveAttrVals(row) {
      //将输入的数据发起请求,保存数据库1.7.5
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        //  服务器接收字符串,我们要把新数组拼接为字符串
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数项失败')
      }

      this.$message.success('修改参数项成功')
    }
  },
  //   计算属性
  computed: {
    //如果按钮需要被禁用,返回true,否则返回false
    isButtonDisabled() {
      if (this.selectedParamsKeys.length !== 3) {
        return true
      }
      return false
    },
    //获取选中的三级分类id
    cateId() {
      if (this.selectedParamsKeys.length === 3) {
        //如果长度不等于3,就不是3级分类,清空
        return this.selectedParamsKeys[2]
      }
      return this.$message.error('不是三级列表')
    },
    //动态计算标题的文本
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 150px;
}
</style>
